import React ,{Component,Fragment} from 'react'
import TodoItem from './TodoItem'

class TodoList extends Component{
    constructor(props){
        super(props);
        this.state = {
            inputValue : 'input',
            list:['1','2']
        }
        this.inputOnChange = this.inputOnChange.bind(this);
        this.buttonOnClick = this.buttonOnClick.bind(this);
        this.liDelItem = this.liDelItem.bind(this);
    }
    componentWillMount(){
        console.log("componentWillMount");
    }
    componentDidMount(){
        console.log("componentDidMount");
    }
    render() {
        return (
            <Fragment>
                <div>
                    <input value={this.state.inputValue} onChange={this.inputOnChange}/>
                    <button onClick={this.buttonOnClick}>提交</button>
                </div>
                <div>
                    <ul>
                        {this.getItem()}
                    </ul>
                </div>
                <TodoItem/>
            </Fragment>
        )
    }
    getItem(){
        return this.state.list.map((item,index)=>{
            return <div key={index} >
                <TodoItem index={index} item = {item} deleteItem={this.liDelItem}/>
            </div>
        })
    }
    inputOnChange(e){
        const value = e.target.value;
        this.setState(()=>({
            inputValue: value
        }))
    }
    buttonOnClick(){
        const list = [...this.state.list,this.state.inputValue];
        this.setState((prevState)=>({
            list:list
        }))
    }
    liDelItem(index){
        this.setState((prevState)=>{
            const list = [...prevState.list];
            list.splice(index,1);
            return {
                list:list,
                inputValue:''
            };
        })
    }
}

export default TodoList;